import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login/index.vue')
  },
  {
    path: '/course',
    name: 'course',
    alias: '/',
    component: () => import(/* webpackChunkName: "course" */ '../views/course/index.vue')
  },
  {
    path: '/course-info/:courseId',
    name: 'course-info',
    component: () => import(/* webpackChunkName: "course-info" */ '../views/course-info/index.vue'),
    props: true,
  },
  {
    path: '/pay/:courseId',
    name: 'pay',
    component: () => import(/* webpackChunkName: "pay" */ '../views/pay/index.vue'),
    props: true,
  },
  {
    path: '/learn',
    name: 'learn',
    component: () => import(/* webpackChunkName: "learn" */ '../views/learn/index.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/lesson-video/:lessonId',
    name: 'lesson-video',
    component: () => import(/* webpackChunkName: "lesson-video" */ '../views/course-info/video.vue'),
    props: true,
  },
  {
    path: '/user',
    name: 'user',
    component: () => import(/* webpackChunkName: "user" */ '../views/user/index.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '*',
    name: 'error-page',
    component: () => import(/* webpackChunkName: "error-page" */ '../views/error-page/index.vue')
  },
]

const router = new VueRouter({
  routes
})

// 路由前置守卫：进入页面前判断当前用户是否有权限
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth) && !store.state.user) {
    next({
      name: 'login',
      query: {
        redirect: to.fullPath
      }
    })
  } else {
    next()
  }
})

export default router
